package org.jeecg.modules.wms.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.jeecg.modules.wms.entity.WmsPurchaseArrivalInspection;
import org.jeecg.modules.wms.mapper.WmsPurchaseArrivalInspectionMapper;
import org.jeecg.modules.wms.service.IWmsPurchaseArrivalInspectionService;
import org.springframework.stereotype.Service;
import lombok.extern.slf4j.Slf4j;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @Description: 采购到货质检结果表
 * @Author: jeecg-boot
 * @Date: 2023-08-10
 * @Version: V1.0
 */
@Service
@Slf4j
@Transactional(rollbackFor = Exception.class)
public class WmsPurchaseArrivalInspectionServiceImpl extends ServiceImpl<WmsPurchaseArrivalInspectionMapper, WmsPurchaseArrivalInspection> implements IWmsPurchaseArrivalInspectionService {

    @Override
    public int deleteByPurchaseOrderId(String purchaseOrderId) {
        return baseMapper.deleteByPurchaseOrderId(purchaseOrderId);
    }
    
    @Override
    public int batchSave(String purchaseOrderId, String purchaseOrderNo, String arrivalDate, 
                        List<Map<String, Object>> details, String username) {
        if (details == null || details.isEmpty()) {
            return 0;
        }
        
        // 不再删除旧数据，而是根据是否有ID判断是新增还是更新
        
        List<WmsPurchaseArrivalInspection> inspectionList = new ArrayList<>();
        Date date = parseDate(arrivalDate);
        Date now = new Date();
        
        for (Map<String, Object> detail : details) {
            String materialId = (String) detail.get("materialId");
            String materialCode = (String) detail.get("materialCode");
            String materialName = (String) detail.get("materialName");
            String materialType = String.valueOf(detail.get("materialType"));
            String specification = (String) detail.get("specification");
            String unit = (String) detail.get("unit");
            String supplierId = (String) detail.get("supplierId");
            String supplierName = (String) detail.get("supplierName");
            String remark = (String) detail.get("remark");
            String evidence = (String) detail.get("evidence");
            
            BigDecimal arrivalQuantity = new BigDecimal(detail.get("arrivalQuantity").toString());
            BigDecimal unqualifiedQuantity = BigDecimal.ZERO;
            BigDecimal qualifiedQuantity;
            
            // 获取不合格数量，如果没有则默认为0
            if (detail.containsKey("unqualifiedQuantity") && detail.get("unqualifiedQuantity") != null) {
                unqualifiedQuantity = new BigDecimal(detail.get("unqualifiedQuantity").toString());
            }
            
            // 直接获取前端传入的合格数量，如果没有则计算
            if (detail.containsKey("qualifiedQuantity") && detail.get("qualifiedQuantity") != null) {
                qualifiedQuantity = new BigDecimal(detail.get("qualifiedQuantity").toString());
            } else {
                // 计算合格数量
                qualifiedQuantity = arrivalQuantity.subtract(unqualifiedQuantity);
            }
            
            // 只有当到货数量大于0时才创建记录
            if (arrivalQuantity.compareTo(BigDecimal.ZERO) > 0) {
                // 创建合格记录
                if (qualifiedQuantity.compareTo(BigDecimal.ZERO) > 0) {
                    WmsPurchaseArrivalInspection qualifiedInspection = new WmsPurchaseArrivalInspection();
                    qualifiedInspection.setPurchaseOrderId(purchaseOrderId);
                    qualifiedInspection.setPurchaseOrderNo(purchaseOrderNo);
                    qualifiedInspection.setMaterialId(materialId);
                    qualifiedInspection.setMaterialCode(materialCode);
                    qualifiedInspection.setMaterialName(materialName);
                    qualifiedInspection.setMaterialType(materialType);
                    qualifiedInspection.setSpecification(specification);
                    qualifiedInspection.setUnit(unit);
                    qualifiedInspection.setArrivalQuantity(arrivalQuantity);
                    qualifiedInspection.setQualifiedQuantity(qualifiedQuantity);
                    qualifiedInspection.setUnqualifiedQuantity(BigDecimal.ZERO);
                    qualifiedInspection.setInspectionResult(1); // 合格
                    qualifiedInspection.setRemark(remark);
                    qualifiedInspection.setEvidence(evidence);
                    qualifiedInspection.setSupplierId(supplierId);
                    qualifiedInspection.setSupplierName(supplierName);
                    qualifiedInspection.setArrivalDate(date);
                    qualifiedInspection.setCreateBy(username);
                    qualifiedInspection.setCreateTime(now);
                    qualifiedInspection.setStatus(0); // 未处理状态
                    
                    inspectionList.add(qualifiedInspection);
                }
            }
        }
        
        if (!inspectionList.isEmpty()) {
            this.saveBatch(inspectionList);
        }
        
        return inspectionList.size();
    }
    
    @Override
    public int batchSaveUnqualified(String purchaseOrderId, String purchaseOrderNo, String arrivalDate, 
                                   List<Map<String, Object>> unqualifiedList, String username) {
        if (unqualifiedList == null || unqualifiedList.isEmpty()) {
            return 0;
        }
        
        List<WmsPurchaseArrivalInspection> inspectionList = new ArrayList<>();
        Date date = parseDate(arrivalDate);
        Date now = new Date();
        
        for (Map<String, Object> unqualified : unqualifiedList) {
            String materialId = (String) unqualified.get("materialId");
            String materialCode = (String) unqualified.get("materialCode");
            String materialName = (String) unqualified.get("materialName");
            String materialType = (String) unqualified.get("materialType");
            String specification = (String) unqualified.get("specification");
            String unit = (String) unqualified.get("unit");
            String supplierId = (String) unqualified.get("supplierId");
            String supplierName = (String) unqualified.get("supplierName");
            String reason = (String) unqualified.get("reason");
            String evidence = (String) unqualified.get("evidence");
            
            BigDecimal unqualifiedQuantity = new BigDecimal(unqualified.get("unqualifiedQuantity").toString());
            
            // 只有当不合格数量大于0时才创建记录
            if (unqualifiedQuantity.compareTo(BigDecimal.ZERO) > 0) {
                WmsPurchaseArrivalInspection inspection = new WmsPurchaseArrivalInspection();
                inspection.setPurchaseOrderId(purchaseOrderId);
                inspection.setPurchaseOrderNo(purchaseOrderNo);
                inspection.setMaterialId(materialId);
                inspection.setMaterialCode(materialCode);
                inspection.setMaterialName(materialName);
                inspection.setMaterialType(materialType);
                inspection.setSpecification(specification);
                inspection.setUnit(unit);
                inspection.setArrivalQuantity(unqualifiedQuantity);
                inspection.setQualifiedQuantity(BigDecimal.ZERO);
                inspection.setUnqualifiedQuantity(unqualifiedQuantity);
                inspection.setInspectionResult(0); // 不合格
                inspection.setUnqualifiedReason(reason);
                inspection.setEvidence(evidence);
                inspection.setSupplierId(supplierId);
                inspection.setSupplierName(supplierName);
                inspection.setArrivalDate(date);
                inspection.setCreateBy(username);
                inspection.setCreateTime(now);
                inspection.setStatus(0); // 未处理状态
                
                inspectionList.add(inspection);
            }
        }
        
        if (!inspectionList.isEmpty()) {
            this.saveBatch(inspectionList);
        }
        
        return inspectionList.size();
    }
    
    /**
     * 解析日期字符串
     */
    private Date parseDate(String dateStr) {
        if (dateStr == null || dateStr.trim().isEmpty()) {
            return new Date();
        }
        
        try {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            return sdf.parse(dateStr);
        } catch (Exception e) {
            log.error("日期解析失败", e);
            return new Date();
        }
    }
    
    /**
     * 获取采购单的到货历史记录
     * 
     * @param purchaseOrderId 采购单ID
     * @return 到货历史记录列表，按到货日期分组
     */
    @Override
    public List<Map<String, Object>> getArrivalHistoryByPurchaseOrderId(String purchaseOrderId) {
        // 按到货日期分组查询
        List<Map<String, Object>> result = new ArrayList<>();
        
        try {
            // 查询所有到货记录，按到货日期分组
            Map<String, List<WmsPurchaseArrivalInspection>> groupedByDate = this.lambdaQuery()
                .eq(WmsPurchaseArrivalInspection::getPurchaseOrderId, purchaseOrderId)
                .orderByDesc(WmsPurchaseArrivalInspection::getArrivalDate)
                .list()
                .stream()
                .collect(java.util.stream.Collectors.groupingBy(
                    inspection -> new SimpleDateFormat("yyyy-MM-dd").format(inspection.getArrivalDate())
                ));
            
            // 转换为前端需要的格式
            for (Map.Entry<String, List<WmsPurchaseArrivalInspection>> entry : groupedByDate.entrySet()) {
                String arrivalDate = entry.getKey();
                List<WmsPurchaseArrivalInspection> inspections = entry.getValue();
                
                // 提取第一条记录的创建人
                String createBy = inspections.get(0).getCreateBy();
                
                // 提取物料明细
                List<Map<String, Object>> details = new ArrayList<>();
                
                // 按物料ID分组，合并同一物料的合格和不合格数量
                Map<String, List<WmsPurchaseArrivalInspection>> groupedByMaterial = inspections.stream()
                    .collect(java.util.stream.Collectors.groupingBy(WmsPurchaseArrivalInspection::getMaterialId));
                
                for (Map.Entry<String, List<WmsPurchaseArrivalInspection>> materialEntry : groupedByMaterial.entrySet()) {
                    List<WmsPurchaseArrivalInspection> materialInspections = materialEntry.getValue();
                    WmsPurchaseArrivalInspection firstInspection = materialInspections.get(0);
                    
                    // 计算总到货数量、合格数量和不合格数量
                    BigDecimal totalArrivalQuantity = BigDecimal.ZERO;
                    BigDecimal totalQualifiedQuantity = BigDecimal.ZERO;
                    BigDecimal totalUnqualifiedQuantity = BigDecimal.ZERO;
                    
                    for (WmsPurchaseArrivalInspection inspection : materialInspections) {
                        if (inspection.getArrivalQuantity() != null) {
                            totalArrivalQuantity = totalArrivalQuantity.add(inspection.getArrivalQuantity());
                        }
                        if (inspection.getQualifiedQuantity() != null) {
                            totalQualifiedQuantity = totalQualifiedQuantity.add(inspection.getQualifiedQuantity());
                        }
                        if (inspection.getUnqualifiedQuantity() != null) {
                            totalUnqualifiedQuantity = totalUnqualifiedQuantity.add(inspection.getUnqualifiedQuantity());
                        }
                    }
                    
                    Map<String, Object> detail = new java.util.HashMap<>();
                    detail.put("materialId", firstInspection.getMaterialId());
                    detail.put("materialCode", firstInspection.getMaterialCode());
                    detail.put("materialName", firstInspection.getMaterialName());
                    detail.put("materialType", firstInspection.getMaterialType());
                    detail.put("specification", firstInspection.getSpecification());
                    detail.put("unit", firstInspection.getUnit());
                    detail.put("arrivalQuantity", totalArrivalQuantity);
                    detail.put("qualifiedQuantity", totalQualifiedQuantity);
                    detail.put("unqualifiedQuantity", totalUnqualifiedQuantity);
                    details.add(detail);
                }
                
                // 创建历史记录
                Map<String, Object> historyRecord = new java.util.HashMap<>();
                historyRecord.put("arrivalDate", arrivalDate);
                historyRecord.put("createBy", createBy);
                historyRecord.put("details", details);
                
                result.add(historyRecord);
            }
            
            return result;
        } catch (Exception e) {
            log.error("获取到货历史记录失败", e);
            return result;
        }
    }
} 